import request from "@/utils/request";
import type { User, PageQuery, PageResponse, ApiResponse } from "@/types";

/**
 * 获取用户列表
 */
export function getUserList(params: PageQuery) {
  return request.get<PageResponse<User>>("/users", params);
}

/**
 * 获取用户详情
 */
export function getUserDetail(id: number) {
  return request.get<User>(`/users/${id}`);
}

/**
 * 创建用户
 */
export function createUser(data: Partial<User>) {
  return request.post<User>("/user/addUser", data);
}

/**
 * 更新用户
 */
export function updateUser(data: Partial<User>) {
  return request.post<User>(`/user/updateUser`, data);
}

/**
 * 删除用户
 */
export function deleteUser(id: number) {
  return request.delete(`/user/deleteUser?id=${id}`);
}

/**
 * 验证原密码并重置密码
 */
export function resetUserPasswordWithOldPassword(data: User) {
  return request.post(`/user/updateUser`, data);
}

/**
 * 启用/禁用用户
 */
export function toggleUserStatus(id: number, isEnable: boolean) {
  return request.put(`/users/${id}/status`, { isEnable });
}

/**
 * 根据组织ID获取用户列表
 */
export function getUsersByOrganize(
  organizeId: number,
  params?: PageQuery & { keyword?: string }
) {
  return request.get<PageResponse<User>>(
    `/user/getUsersByOrgId?orgId=${organizeId}`,
    params
  );
}

/**
 * 搜索用户
 */
export function searchUsers(keyword: string, params?: PageQuery) {
  return request.get<PageResponse<User>>("/users/search", {
    keyword,
    ...params,
  });
}

/**
 * 批量删除用户
 */
export function batchDeleteUsers(ids: number[]) {
  return request.post("/users/batch-delete", { ids });
}

/**
 * 导入用户
 */
export function importUsers(file: File) {
  const formData = new FormData();
  formData.append("file", file);
  return request.post<
    ApiResponse<{
      success: number;
      failed: number;
      errors: string[];
    }>
  >("/users/import", formData);
}

/**
 * 获取用户角色列表
 */
export function getUserRoles(userId: number) {
  return request.get(`/users/${userId}/roles`);
}

/**
 * 设置用户角色
 */
export function setUserRoles(userId: number, roleIds: number[]) {
  return request.post(`/users/${userId}/roles`, { roleIds });
}

/**
 * 获取用户组织列表
 */
export function getUserOrganizes(userId: number) {
  return request.get(`/users/${userId}/organizes`);
}

/**
 * 设置用户组织
 */
export function setUserOrganizes(userId: number, organizeIds: number[]) {
  return request.post(`/users/${userId}/organizes`, { organizeIds });
}

/**
 * 获取角色下的所有用户
 */
export function $getUsersByRole(roleId: number) {
  return request.get(`/user/getUsersByRoleId?id=${roleId}`);
}

/**
 * 获取用户详情
 */
export function $getUserDetail(id: number) {
  return request.get<User>(`/user/getUserDetails?id=${id}`);
}

/**
 * 导出用户
 */
export function $exportUsers() {
  return request.post("/user/exportUserInfos", { responseType: "blob" });
}
